package com.samsung.spen.sshare.explorer.choosefiles;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;

import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.samsung.spen.sshare.R;
import com.samsung.spen.sshare.explorer.util.FileAdapter;
import com.samsung.spen.sshare.explorer.util.FileExtend;
import com.samsung.spen.sshare.explorer.util.SConfig;

public class FilesChooseActivity extends ListActivity {

	static Toast mToast;
	TextView tvDir;

	static ArrayList<FileExtend> data;
	FileAdapter adapter;

	Handler mHandler;

	ArrayList<String> arrayListFilePaths = new ArrayList<String>();
	ArrayList<String> arrayList;

	static Dialog dialogInfomation;
	static ProgressDialog progressDialog = null;
	static Builder builder;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.exp_files_choose);

		tvDir = (TextView) findViewById(R.id.tv_directory);

		mHandler = new Handler();

		new BeginLoad().execute();

		View view = LayoutInflater.from(this).inflate(
				R.layout.exp_files_choose_header, null);
		CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBox1);

		checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {

				SConfig.FLAG_SELECT_ALL = isChecked;
				refresh();
			}
		});

		Button button = (Button) view.findViewById(R.id.btnParent);

		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (SConfig.rootPath.equals(SConfig.rootPathDef)) {

					showToast("This is root folder!!!");
					return;
				}

				String parent = new File(SConfig.rootPath).getParent();
				SConfig.rootPath = parent;
				refresh();
			}
		});

		dialogInfomation = new Dialog(this);
		dialogInfomation.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialogInfomation.setContentView(R.layout.exp_file_info);

		this.getListView().addHeaderView(view);
		// setListAdapter(adapter);
		arrayList = getIntent()
				.getStringArrayListExtra(SConfig.PATH_LIST_FILES);

		getListView().setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {

				FileExtend file = data.get(arg2 - 1);
				//showDialog(file.getFile());

				showDialog(file);
				return true;
			}
		});
		// getListView().setOnItemClickListener(new OnItemClickListener() {
		//
		// @Override
		// public void onItemClick(AdapterView<?> arg0, View arg1, int position,
		// long arg3) {
		// // final ProgressDialog dialog = getProgressDialog();
		// data = getFileArray();
		// final File f = data.get(position - 1).getFile();
		// if(f.isDirectory()) {
		// Config.rootPath = f.getAbsolutePath();
		// }else {
		// data.get(position-1).flag_choosed=!data.get(position-1).flag_choosed;
		// }
		// refresh();
		// }
		// });

		this.getListView().setDescendantFocusability(
				ListView.FOCUS_BLOCK_DESCENDANTS);
		getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);

	}

	private ProgressDialog getProgressDialog() {

		if (progressDialog == null) {

			progressDialog = ProgressDialog.show(this, "", "loading...");
			return progressDialog;
		}

		return progressDialog;
	}

	public void showDialog(FileExtend fileExtend) {

		if (dialogInfomation.isShowing())
			dialogInfomation.dismiss();

		TextView tvName = (TextView) dialogInfomation
				.findViewById(R.id.info_name);
		TextView tvTime = (TextView) dialogInfomation
				.findViewById(R.id.info_time);
		TextView tvSize = (TextView) dialogInfomation
				.findViewById(R.id.info_size);
		TextView tvContent = (TextView) dialogInfomation
				.findViewById(R.id.info_content);
		Button btnOk = (Button) dialogInfomation.findViewById(R.id.btn_ok);

		btnOk.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				dialogInfomation.dismiss();
			}
		});

		File file = fileExtend.getFile();

		tvName.setText(file.getName());

		long lastMdf = file.lastModified();
		Calendar cld = Calendar.getInstance();
		cld.setTimeInMillis(lastMdf);

		tvTime.setText(cld.get(Calendar.DAY_OF_MONTH) + "/"
				+ cld.get(Calendar.MONTH) + "/" + cld.get(Calendar.YEAR) + " "
				+ cld.get(Calendar.HOUR_OF_DAY) + ":"
				+ cld.get(Calendar.MINUTE));

		tvSize.setText(FileExtend.getLeng(file) + " bytes");

		int folders = 0;
		int files = 0;

		for (File item : file.listFiles()) {

			if (item.isDirectory())
				folders++;
			else
				files++;
		}

		if (folders == 0 && files == 0) {
			tvContent.setText("This folder is empty");

		} else {
			tvContent.setText("This folder contain " + folders + " folders, "
					+ files + " files.");
		}

		dialogInfomation.show();
	}
	
	public void showDialog(File file) {

		if (dialogInfomation.isShowing())
			dialogInfomation.dismiss();

		TextView tvName = (TextView) dialogInfomation
				.findViewById(R.id.info_name);
		TextView tvTime = (TextView) dialogInfomation
				.findViewById(R.id.info_time);
		TextView tvSize = (TextView) dialogInfomation
				.findViewById(R.id.info_size);
		TextView tvContent = (TextView) dialogInfomation
				.findViewById(R.id.info_content);
		Button btnOk = (Button) dialogInfomation.findViewById(R.id.btn_ok);

		btnOk.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				dialogInfomation.dismiss();
			}
		});

		tvName.setText(file.getName());
		long lastMdf = file.lastModified();
		Calendar cld = Calendar.getInstance();
		cld.setTimeInMillis(lastMdf);
		tvTime.setText(cld.get(Calendar.DAY_OF_MONTH) + "/"
				+ cld.get(Calendar.MONTH) + "/" + cld.get(Calendar.YEAR) + " "
				+ cld.get(Calendar.HOUR_OF_DAY) + ":"
				+ cld.get(Calendar.MINUTE));

		tvSize.setText(file.length() + " bytes");
		int folders = 0;
		int files = 0;

		for (File item : file.listFiles()) {
			if (item.isDirectory())
				folders++;
			else
				files++;
		}

		if (folders == 0 && files == 0) {
			tvContent.setText("This folder is empty");

		} else {
			tvContent.setText("This folder contain " + folders + " folders, "
					+ files + " files.");
		}

		dialogInfomation.show();
	}

	@Override
	protected void onListItemClick(ListView l, View v, final int position,
			long id) {
		super.onListItemClick(l, v, position, id);

		// final ProgressDialog dialog = getProgressDialog();
		data = getFileArray();
		final File f = data.get(position - 1).getFile();

		if (f.isDirectory()) {

			SConfig.rootPath = f.getAbsolutePath();
		} else {

			data.get(position - 1).flag_choosed = !data.get(position - 1).flag_choosed;
		}

		refresh();

	}

	public ArrayList<FileExtend> getFileArray() throws NullPointerException {

		ArrayList<FileExtend> listFile = new ArrayList<FileExtend>();

		File[] data = new File(SConfig.rootPath).listFiles();

		if (data != null) {

			for (File file : data) {

				if (file != null) {

					FileExtend fExtend = new FileExtend(file);
					listFile.add(fExtend);
				}

			}
		}

		Collections.sort(listFile);
		return listFile;
	}

	public void refresh(ArrayList<FileExtend> files) {

		Collections.sort(files);

		if (files == null) {

			showToast("Folder is Empty!");
			setListAdapter(null);
			return;
		}

		adapter = new FileAdapter(this.getApplicationContext(), mHandler,
				R.layout.exp_file_choose_item, files);

		setListAdapter(adapter);
		// adapter.notifyDataSetChanged();
		tvDir.setText(SConfig.rootPath);

	}

	@Override
	protected void onStart() {
		super.onStart();
		refresh();
	}

	public void refresh() {
		// data = getFileArray();
		// refresh(data);
		new LoadFiles().execute();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if ((keyCode == KeyEvent.KEYCODE_BACK)) {

			if (SConfig.rootPath.equals(SConfig.rootPathDef)) {

				FilesChooseActivity.this.finish();
				return true;
			}

			if (SConfig.FLAG_SELECT_ALL) {
				SConfig.FLAG_SELECT_ALL = false;
			}

			String parent = new File(SConfig.rootPath).getParent();
			SConfig.rootPath = parent;

			refresh();
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}

	public void showToast(final String text) {
		mHandler.post(new Runnable() {

			public void run() {
				if (mToast == null)
					mToast = Toast.makeText(FilesChooseActivity.this, text,
							Toast.LENGTH_SHORT);

				mToast.setGravity(Gravity.CENTER, 0, 0);
				mToast.setText(text);
				mToast.show();
			}
		});

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.exp_activity_main, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {

		case R.id.menu_done:

			for (FileExtend iterable_element : data) {

				if (iterable_element.flag_choosed
						&& !iterable_element.getFile().isDirectory()) {

					arrayListFilePaths.add(iterable_element.getFile()
							.getAbsolutePath());

				}
			}

			int temp = arrayListFilePaths.size();
			// if (temp > 0) {

			if (arrayList != null && arrayList.size() > 0) {

				if (temp > 0) {
					processDone();

				} else {

					if (temp == 0) {

						Intent intent4 = getIntent();
						intent4.putStringArrayListExtra(
								SConfig.PATH_LIST_FILES, arrayList);
						setResult(RESULT_OK, intent4);

						this.finish();

					}
				}

			} else {

				if (temp > 0) {

					// Intent intent = new Intent(this,
					// FilesSelectedActivity.class);
					// intent.putStringArrayListExtra(SConfig.PATH_LIST_FILES,
					// arrayListFilePaths);
					// startActivity(intent);
					// this.finish();
					processDone();

				} else {

					builder = getDialog();
					builder.setTitle("Info").setIcon(R.drawable.exp_all)
							.setMessage("No item selected!!!")
							.setPositiveButton("Close", null).show();
				}

			}

			SConfig.FLAG_SELECT_ALL = false;

			break;

		case R.id.menu_select_all:
			SConfig.FLAG_SELECT_ALL = !SConfig.FLAG_SELECT_ALL;
			refresh();
			break;

		case R.id.menu_sort:

			if (SConfig.FLAG_SORT == SConfig.FLAG_SORT_BY_NAME) {

				SConfig.FLAG_SORT = SConfig.FLAG_SORT_BY_SIZE;
				item.setTitle("sort items by name");

			} else {

				SConfig.FLAG_SORT = SConfig.FLAG_SORT_BY_NAME;
				item.setTitle("sort items by size");
			}
			refresh();
			break;
		default:
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	private Builder getDialog() {

		if (builder == null) {

			builder = new Builder(this);
		}

		return builder;

	}

	public void processDone() {

		ArrayList<String> list = new ArrayList<String>();

		for (String iterable_element : arrayList) {

			for (String iterable_element1 : arrayListFilePaths) {

				if (iterable_element.equalsIgnoreCase(iterable_element1)) {

					list.add(iterable_element);
				}
			}
		}

		for (String string : list) {
			arrayList.remove(string);
		}

		for (String iterable_element2 : arrayListFilePaths) {

			arrayList.add(iterable_element2);

		}

		Intent local = getIntent();
		local.putStringArrayListExtra(SConfig.PATH_LIST_FILES, arrayList);
		setResult(RESULT_OK, local);

		this.finish();

	}

	// Thread
	private class LoadFiles extends AsyncTask<Void, Integer, Void> {

		private ProgressDialog dialog;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog = getProgressDialog();
		}

		@Override
		protected Void doInBackground(Void... params) {

			data = getFileArray();
			Collections.sort(data);

			if (data == null) {

				showToast("Folder is Empty!");
				setListAdapter(null);
				return null;
			}

			adapter = new FileAdapter(FilesChooseActivity.this, mHandler,
					R.layout.exp_file_choose_item, data);

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);

			setListAdapter(adapter);
			tvDir.setText(SConfig.rootPath);
			dialog.dismiss();
		}
	}

	private class BeginLoad extends AsyncTask<Void, Void, Void> {

		private ProgressDialog dialog;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog = getProgressDialog();
		}

		@Override
		protected Void doInBackground(Void... params) {

			data = getFileArray();

			adapter = new FileAdapter(FilesChooseActivity.this, mHandler,
					R.layout.exp_file_choose_item, data);
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);

			setListAdapter(adapter);
			tvDir.setText(SConfig.rootPath);
			dialog.dismiss();
		}
	}
}
